﻿#include "mainwidget.h"
#include "./ui_mainwidget.h"
#include "addcommodity.h"
#include "inbound.h"
#include "delivery.h"
#include "datasum.h"
#include "editcommodity.h"

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);

    //设置主窗口背景颜色
    QPalette plt;
    plt.setColor(QPalette::Window,QColor(180,180,180));
    this->setPalette(plt);
    ConnectMySQLDBFunc();

    TableWidgetInit();
}

MainWidget::~MainWidget()
{
    delete ui;
}


void MainWidget::ConnectMySQLDBFunc()
{
    // QSqlDatabase: available drivers: QSQLITE QMARIADB QMYSQL QMYSQL3 QODBC QODBC3
    QSqlDatabase db=QSqlDatabase::addDatabase("QMARIADB");
    db.setHostName("127.0.0.1");
    db.setPort(3306);
    db.setDatabaseName("stockmsdb");
    db.setUserName("root");
    db.setPassword("112233");

    bool is_success=db.open();

    if(!is_success)//判断连接数据库是否成功
    {
        QMessageBox::information(this,"提示","数据库连接失败");
    }
}

//新增商品
void MainWidget::on_AddBtn_clicked()
{
    AddCommodity *addlg=new AddCommodity();
    addlg->exec();
    on_SearchBtn_clicked();
}

//删除商品（标记删除，保留历史记录）
void MainWidget::on_DeleteBtn_clicked()
{
    // 获取当前选中的行
    int irow = ui->ListDATA->currentRow();
    if (irow < 0) {
        QMessageBox::information(this, "提示", "请先选择要删除的商品！");
        return;
    }

    // 获取商品ID和名称
    QString stockId = ui->ListDATA->model()->index(irow, 0).data().toString();
    QString stockName = ui->ListDATA->model()->index(irow, 1).data().toString();
    QString stockAmount = ui->ListDATA->model()->index(irow, 2).data().toString();

    if (stockId.isEmpty()) {
        QMessageBox::critical(this, "错误", "无法获取商品编号");
        return;
    }

    // 获取完整商品信息
    QSqlQuery infoQuery;
    infoQuery.prepare("SELECT StockId, StockName, StockAmount, StockUnitprice, "
                      "Supplier, Director, WareHousetime, Remarks "
                      "FROM commoditydatatable WHERE StockId = ?");
    infoQuery.addBindValue(stockId);

    if (!infoQuery.exec() || !infoQuery.next()) {
        QMessageBox::critical(this, "错误", "无法获取商品详细信息");
        return;
    }

    // 构建商品详细信息
    QString productInfo = QString(
                              "════════════════════════════════════════\n"
                              "           商品详细信息\n"
                              "════════════════════════════════════════\n"
                              "商品编号: %1\n"
                              "商品名称: %2\n"
                              "库存数量: %3\n"
                              "商品单价: ¥%4\n"
                              "供应商: %5\n"
                              "负责人: %6\n"
                              "入库时间: %7\n"
                              "备注: %8\n"
                              "════════════════════════════════════════"
                              ).arg(
                                  infoQuery.value(0).toString(),
                                  infoQuery.value(1).toString(),
                                  infoQuery.value(2).toString(),
                                  infoQuery.value(3).toString(),
                                  infoQuery.value(4).toString(),
                                  infoQuery.value(5).toString(),
                                  infoQuery.value(6).toDateTime().toString("yyyy-MM-dd hh:mm:ss"),
                                  infoQuery.value(7).toString()
                                  );

    // 第一次确认 - 显示完整商品信息
    int firstConfirm = QMessageBox::question(
        this,
        "第一次确认 - 商品信息确认",
        QString("您即将标记删除以下商品，请仔细核对信息：\n\n%1\n\n是否确认要标记删除该商品？").arg(productInfo),
        QMessageBox::Yes | QMessageBox::No,
        QMessageBox::No
        );

    if (firstConfirm != QMessageBox::Yes) {
        QMessageBox::information(this, "提示", "删除操作已取消");
        return;
    }

    // 第二次确认 - 说明删除方式
    int secondConfirm = QMessageBox::information(
        this,
        "第二次确认 - 删除方式说明",
        QString("删除方式说明：\n\n"
                "此删除操作将：\n"
                "✅ 标记商品为已删除状态（不在列表中显示）\n"
                "✅ 保留所有入库记录\n"
                "✅ 保留所有出库记录\n"
                "✅ 在操作记录中添加删除记录\n"
                "✅ 保留完整的库存变动历史\n\n"
                "商品 '%1' 将不再出现在商品列表中，但历史记录将完整保留。\n\n"
                "是否确认继续？").arg(stockName),
        QMessageBox::Yes | QMessageBox::No,
        QMessageBox::No
        );

    if (secondConfirm != QMessageBox::Yes) {
        QMessageBox::information(this, "提示", "删除操作已取消");
        return;
    }

    // 第三次确认 - 最终确认
    int thirdConfirm = QMessageBox::warning(
        this,
        "第三次确认 - 最终确认",
        QString("最终确认！\n\n"
                "您即将标记删除商品 '%1' (编号: %2)\n\n"
                "商品将不再显示在列表中，但所有历史记录将完整保留。\n\n"
                "确认要执行此操作吗？").arg(stockName, stockId),
        QMessageBox::Yes | QMessageBox::No,
        QMessageBox::No
        );

    if (thirdConfirm != QMessageBox::Yes) {
        QMessageBox::information(this, "提示", "删除操作已取消");
        return;
    }

    // 执行标记删除操作
    QSqlQuery result;
    QSqlDatabase::database().transaction();

    try {
        QString operatorName = "系统管理员"; // 实际操作人，可以从界面获取

        // 1. 在stock_operations表中添加"删除"操作记录
        // 现在可以直接使用"删除"作为操作类型
        QString insertDeleteRecordSQL =
            "INSERT INTO stock_operations (operation_type, stock_id, stock_name, "
            "operation_amount, operator, operation_time, remarks) "
            "VALUES ('删除', ?, ?, 0, ?, NOW(), ?)";

        result.prepare(insertDeleteRecordSQL);
        result.addBindValue(stockId);
        result.addBindValue(stockName);
        result.addBindValue(operatorName);
        result.addBindValue(QString("商品被标记删除，删除时库存数量：%1").arg(stockAmount));

        if (!result.exec()) {
            throw QString("添加删除操作记录失败: %1").arg(result.lastError().text());
        }

        // 2. 实际删除商品记录
        QString deleteCommoditySQL =
            "DELETE FROM commoditydatatable WHERE StockId = ?";

        result.prepare(deleteCommoditySQL);
        result.addBindValue(stockId);

        if (!result.exec()) {
            throw QString("删除商品记录失败: %1").arg(result.lastError().text());
        }

        // 提交事务
        QSqlDatabase::database().commit();

        // 成功提示
        QMessageBox::information(
            this,
            "删除成功",
            QString("✅ 商品删除成功！\n\n"
                    "商品 '%1' (编号: %2) 已从系统中删除。\n\n"
                    "操作完成：\n"
                    "✓ 商品基本信息已删除\n"
                    "✓ 添加了删除操作记录\n"
                    "✓ 保留了所有出入库历史记录\n"
                    "✓ 保留了完整的库存变动历史").arg(stockName, stockId)
            );

        // 刷新显示
        on_SearchBtn_clicked();

    } catch (const QString &error) {
        // 回滚事务
        QSqlDatabase::database().rollback();
        QMessageBox::critical(
            this,
            "删除失败",
            QString("❌ 删除操作失败！\n\n错误信息：%1").arg(error)
            );
    }
}

//商品入库
void MainWidget::on_StoreBtn_clicked()
{
    // 获取当前选中的行
    int irow = ui->ListDATA->currentRow();
    if (irow < 0) {
        QMessageBox::information(this, "提示", "请先选择商品！");
        return;
    }
    QString stockId = ui->ListDATA->model()->index(irow, 0).data().toString();
    Inbound *inlg=new Inbound(nullptr, stockId);
    inlg->exec();
    on_SearchBtn_clicked();
}

//商品出库
void MainWidget::on_OutboundBtn_clicked()
{
    // 获取当前选中的行
    int irow = ui->ListDATA->currentRow();
    if (irow < 0) {
        QMessageBox::information(this, "提示", "请先选择商品！");
        return;
    }
    QString stockId = ui->ListDATA->model()->index(irow, 0).data().toString();
    Delivery *deliverlg=new Delivery(nullptr, stockId);
    deliverlg->exec();
    on_SearchBtn_clicked();
}
//导出数据:生成excel问价并保存
void MainWidget::on_ExportDataBtn_clicked()
{
    // 保存文件扩展名为.xls
    QDateTime time;
    QString strTemp;

    time=QDateTime::currentDateTime();//获取系统时间作为文件名
    strTemp=time.toString("yyyy-MM-dd-hhmmss");

    //QMessageBox::information(this,"测试",strTemp);
    QString strfilename=QFileDialog::getSaveFileName(this,tr("Excel Files"),QString("%1%2.xls").arg(strTemp,"-库存信息"),tr("Excel Files(*.xls)"));
    //QMessageBox::information(this,"测试",strfilename);
    if(!strfilename.isEmpty())
    {
        QAxObject *Excel=new QAxObject;
        if(Excel->setControl("Excel.Application"))
        {
            Excel->dynamicCall("SetVisible (bool Visible)",false);
            Excel->setProperty("DisplayAlerts",false);

            QAxObject *workbooks=Excel->querySubObject("WorkBooks");
            workbooks->dynamicCall("Add");
            QAxObject *workbook=Excel->querySubObject("ActiveWorkBook");
            QAxObject *worksheet=workbook->querySubObject("Worksheets(int)",1);
            QAxObject *cell;
            for(int i=1;i<=ui->ListDATA->columnCount();i++)
            {
                cell=worksheet->querySubObject("Cells(int,int)",1,i);
                cell->setProperty("RowHeight",38);
                cell->dynamicCall("SetValue(const QString&)",ui->ListDATA->horizontalHeaderItem(i-1)->data(0).toString());
            }
            for(int i=2;i<=ui->ListDATA->rowCount()+1;i++)
            {
                for(int j=1;j<=ui->ListDATA->columnCount();j++)
                {
                    /*cell=worksheet->querySubObject("Cells(int,int)",i,j);
                    cell->dynamicCall("SetValue(const QString&)",ui->ListDATA->item(i-2,j-1)->text()+"\t");*/
                    QTableWidgetItem *item = ui->ListDATA->item(i - 2, j - 1);
                    QString text = item ? item->text() + "\t" : "";
                    QAxObject *cell = worksheet->querySubObject("Cells(int,int)", i, j);
                    cell->dynamicCall("SetValue(const QString&)", text);
                }
            }

            workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(strfilename));
            workbook->dynamicCall("Close()");
            Excel->dynamicCall("Quit()");
            delete Excel;
            Excel=NULL;
        }
    }
}

//数据汇总
void MainWidget::on_SummaryBtn_clicked()
{
    DataSum *sublg=new DataSum();
    sublg->exec();
}


void MainWidget::on_SearchBtn_clicked()
{
    ui->ListDATA->clear();
    my_Init();
    if(ui->NumberlEt->text().isEmpty())
    {
        my_search("select *from commoditydatatable");
    }
    else
    {
        QString strid="stockId=";

        strid=strid+ui->NumberlEt->text();

        QString str=QString("select *from commoditydatatable where %1").arg(strid);

        my_search(str);
    }

}
//表单初始化函数
void MainWidget::TableWidgetInit()
{
    my_Init();
    my_search("select *from commoditydatatable");


}
void MainWidget::my_search(QString str)
{
    QSqlQuery sql;
    sql.exec(str);

    int i=0;
    while(sql.next())
    {
        QString strId=sql.value(0).toString();
        QString strName=sql.value(1).toString();
        QString strAmount=sql.value(2).toString();
        QString strUnitPrice=sql.value(3).toString();
        QString strSupplier=sql.value(4).toString();
        QString strDirector=sql.value(5).toString();
        QString strWareHouseTime=sql.value(6).toString();
        QString strDeliveryTime=sql.value(7).toString();
        QString strRemarks=sql.value(8).toString();

        ui->ListDATA->setItem(i,0,new QTableWidgetItem(strId));
        ui->ListDATA->setItem(i,1,new QTableWidgetItem(strName));
        ui->ListDATA->setItem(i,2,new QTableWidgetItem(strAmount));
        ui->ListDATA->setItem(i,3,new QTableWidgetItem(strUnitPrice));
        ui->ListDATA->setItem(i,4,new QTableWidgetItem(strSupplier));
        ui->ListDATA->setItem(i,5,new QTableWidgetItem(strDirector));
        ui->ListDATA->setItem(i,6,new QTableWidgetItem(strWareHouseTime));
        ui->ListDATA->setItem(i,7,new QTableWidgetItem(strDeliveryTime));
        ui->ListDATA->setItem(i,8,new QTableWidgetItem(strRemarks));
        i++;
    }
}

void MainWidget::my_Init()
{
    ui->ListDATA->setColumnCount(9);
    ui->ListDATA->setRowCount(200);
    ui->ListDATA->setHorizontalHeaderLabels
        (QStringList()<<"商品编号"<<"名称"<<"数量"<<"单价"<<"供应商家"<<"负责人"<<"入库时间"<<"出库时间"<<"备注");

    ui->ListDATA->setColumnWidth(0,80);
    ui->ListDATA->setColumnWidth(1,150);
    ui->ListDATA->setColumnWidth(2,80);
    ui->ListDATA->setColumnWidth(3,80);
    ui->ListDATA->setColumnWidth(4,300);
    ui->ListDATA->setColumnWidth(5,80);
    ui->ListDATA->setColumnWidth(6,250);
    ui->ListDATA->setColumnWidth(7,250);
    ui->ListDATA->setColumnWidth(8,180);
}

// 修改商品
void MainWidget::on_EditBtn_clicked()
{
    // 获取当前选中的行
    int currentRow = ui->ListDATA->currentRow();
    if (currentRow < 0) {
        QMessageBox::information(this, "提示", "请先选择要修改的商品！");
        return;
    }

    // 获取商品ID
    QTableWidgetItem *idItem = ui->ListDATA->item(currentRow, 0);
    if (!idItem) {
        QMessageBox::warning(this, "错误", "无法获取商品ID！");
        return;
    }

    QString stockId = idItem->text();

    // 打开修改商品对话框
    EditCommodity editDlg(this, stockId);
    if (editDlg.exec() == QDialog::Accepted) {
        // 修改成功，刷新表格显示
        on_SearchBtn_clicked();
        // QMessageBox::information(this, "提示", "商品信息修改成功！");
    }
}

